package middleware

import (
	"gin-YiStudio-V1/common"
	"gin-YiStudio-V1/common/consts"
	"gin-YiStudio-V1/common/response"
	"gin-YiStudio-V1/dao/model"
	"github.com/astaxie/beego/logs"
	"github.com/gin-gonic/gin"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		tokenString := context.GetHeader("Authorization")
		logs.Info("登录前置鉴权Token begin, token={%v}", tokenString)

		//验证token格式
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			response.Bad(context, consts.AuthValidatorErrorCode, nil, consts.AuthValidatorErrorDesc)
			context.Abort()
			return
		}

		tokenString = tokenString[7:]

		//验证token
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			response.Bad(context, consts.AuthValidatorErrorCode, nil, consts.AuthValidatorErrorDesc)
			context.Abort()
			return
		}

		//验证通过获取Claims中的UserId
		userId := claims.UserId
		var user model.User
		common.DB.First(&user, userId)

		if user.ID == 0 {
			response.Bad(context, consts.AuthValidatorErrorCode, nil, consts.AuthValidatorErrorDesc)
			context.Abort()
			return
		}

		context.Set("user", user)
		context.Next()

	}
}
